/*
 ============================================================================
 Name        : file_sys_test.c
 Author      : liu.sh
 Version     :
 Copyright   : Your copyright notice
 Description : Hello World in C, Ansi-style
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "mail_file_opt.h"

#define TMP_FILE "tmp_file"

static char *test_path = NULL;
static int loop_times = 0;
static int file_size = 0;
static int test_index = 0;


typedef struct _report_res{
	time_t start_time;
	time_t end_time;
}report_res_t;

int pre_report(report_res_t *p_res)
{
	p_res->start_time = time(NULL);
	return 0;
}

int post_report(report_res_t *p_res)
{
	double total_seconds = 0;
	double per_seconds = 0;
	p_res->end_time = time(NULL);
	total_seconds = difftime(p_res->end_time, p_res->start_time);
	per_seconds = total_seconds / loop_times;

	double total_bytes = (double)loop_times*(double)file_size;
	double total_Mbytes = total_bytes / (1 << 20);
	double wr_rate = total_Mbytes / total_seconds;

	printf("==========start at: %s", ctime(&p_res->start_time));
	printf("run time: [%.2f]\n", total_seconds);
	printf("per time: [%.2f]\n", per_seconds);
	printf("all byte: [%.2f]\n", total_bytes);
	printf("all MB  : [%.2f]\n", total_Mbytes);
	printf("wr rate : [%.2f]\n", wr_rate);
	printf("==========end   at: %s", ctime(&p_res->end_time));

	return 0;
}

int init_arguments(int argc, char **argv)
{
	if (5 != argc) {
		fprintf(stderr, "Usage: test_path loop_times file_size test_index\n");
		return -1;
	}

	test_path = argv[1];
	loop_times = atoi(argv[2]);
	file_size = atoi(argv[3]);
	test_index = atoi(argv[4]);
	return 0;
}

int test_no01(report_res_t *p_res)
{
	int i = 0;
	int ret = 0;
	int read_offset = 0;
	int read_len = 0;
	int real_file_size = 0;
	int pf = 0;
	char path_file[256] = {};
	char buff[10240] = {};

	sprintf(path_file, "%s/%s", test_path, TMP_FILE);


	for(i = 0; i < loop_times; i ++)
	{
		memset(buff, 'a', sizeof(buff));
		real_file_size = 0;
		read_offset = 0;

		pf = adpt_sys_open(TMP_FILE, test_path);

		while(1)
		{
			real_file_size += adpt_sys_write(pf, buff, sizeof(buff));
			if(real_file_size > file_size)
			{
				break;
			}
		}

		for(read_offset = 0; read_offset < real_file_size; read_offset += read_len)
		{
			read_len = adpt_sys_read(pf, read_offset, buff, sizeof(buff));
		}

		adpt_sys_close(pf);
		pf = 0;
		adpt_sys_delete(TMP_FILE, test_path);
	}

	return 0;
}

int main(int argc, char **argv)
{
	report_res_t result = {};
	int ret = 0;
	if(init_arguments(argc, argv) < 0)
	{
		exit(-1);
	}

	pre_report(&result);
	switch(test_index)
	{
		case 1:
			ret = test_no01(&result);
			break;
		default:
			break;
	};

	if(!ret)
	{
		post_report(&result);
	}
	else
	{
		fprintf(stderr, "test excute fail!\n");
	}

	exit(0);
}
